#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include "Tentacle.h"
#include "include.h"
#include "GL/glut.h"

Tentacle::Tentacle(TextureManager * textureManager, char * texture, Vector2D * textureVertices, int numPoints, Vector2D position, Vector2D endPoint)
{
	time = rand()/(double)RAND_MAX * 1000.0;
	
	this->textureManager = textureManager;
	this->numPoints = numPoints;
	this->anchorPoint = position;
	this->endPoint = endPoint;
	this->originalEndPoint = endPoint;
	//for(int i = 0; i < 4; i++)
	//	this->textureVertices[i] = textureVertices[i];
	memcpy(this->textureVertices, textureVertices, sizeof(Vector2D)*4);
	for(int i = 0; i < 4; i++)
		printf("START texture[%d] = (%f, %f)\n", i, this->textureVertices[i].x,this->textureVertices[i].y);
	maxLength = endPoint.Magnitude();
	
	
	if(textureManager)
	{
		if(!textureManager->LoadTexture(texture))
		{
			printf("Failed to load %s\n", texture);
		}
		else
			textureIndex = textureManager->TextureIndex(texture);
	}
	
	
}
Tentacle::~Tentacle()
{
	printf("Deleting tentacle\n");
}
void Tentacle::Think(double elapsedTime)
{
	time += elapsedTime;	

	//endPoint.x = maxLength * cos(2*PI*time);
	//endPoint.y = maxLength * sin(2*PI*time);
}
void Tentacle::Draw()
{
	float spacing = endPoint.Magnitude()/numPoints;
	float phaseSpacing = 2.0 * PI / numPoints;
	
	//glColor3f(0.321,0.569,0.235);
	glColor3f(1,1,1);
	glEnable(GL_TEXTURE_2D);
	if(textureManager)
		textureManager->EnableTexture(textureIndex);
	glBegin(GL_QUADS);
	
	Vector2D lastPoint = anchorPoint;
	float lastWidth = maxLength/3;
	float widthStep = lastWidth/(numPoints-1);
	
	
	for(int i = 1; i < numPoints - 1; i++)
	{
		float amplitude = 3 * sin(4*PI * time + phaseSpacing * i);
		Vector2D direction = !endPoint;
		Vector2D pointPosition = anchorPoint + direction * spacing * i;
		
		direction = Vector2D(-direction.y, direction.x);
		pointPosition = pointPosition + amplitude * direction;
		
		//glVertex2f(lastPoint.x, lastPoint.y);
		//glVertex2f(pointPosition.x, pointPosition.y);
		
		float width = lastWidth - widthStep;
		Vector2D vertices[4] = {lastPoint + direction * lastWidth, 
								pointPosition + direction * width,
								pointPosition - direction * width,
								lastPoint - direction * lastWidth};		
		for(int x=0; x < 4; x++)
		{
			glTexCoord2f(textureVertices[x].x, textureVertices[x].y);
			glVertex2f(vertices[x].x, vertices[x].y);
		}
		lastPoint = pointPosition;
		lastWidth = width;
	}	
	
	//Vector2D finalPoint = anchorPoint + endPoint;
	//glVertex2f(lastPoint.x, lastPoint.y);
	//glVertex2f(finalPoint.x, finalPoint.y);
	glEnd();
	
}
